<template>
    <div class="search_container">
        <el-form :inline="true" :model="search">
            <el-form-item label="角色名">
                <el-input v-model="search.roleName" placeholder="请输入关键词" />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="search.active" placeholder="请选择状态">
                    <el-option label="激活" :value="true" />
                    <el-option label="禁用" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="resetSearch">重置</el-button>
            </el-form-item>
        </el-form>

        <el-form :inline="true" :model="search">
            <el-form-item>
                <el-button type="primary" @click="handleDialog(null)">新增</el-button>

                <el-popover :width="380" trigger="click">
                    <template #reference>
                        <el-button type="success">导入</el-button>
                    </template>
                    <el-upload accept=".xlsx" v-model:file-list="fileList" :on-change="handleChange"
                        :http-request="designUpload">
                        <el-button type="primary">文件上传</el-button>
                        <template #tip>
                            <el-button type="success" style="margin-left:10px" @click="itemplateData">模版下载</el-button>
                            <div class="el-upload__tip">
                                仅支持xlsx模版文件,若没有模版文件,请点击模版下载
                            </div>
                        </template>
                    </el-upload>
                </el-popover>
                <el-popover :width="380" trigger="click">
                    <template #reference>
                        <el-button type="warning">导出</el-button>
                    </template>
                    <el-button type="primary" @click="exportData(search, false)">此页</el-button>
                    <el-button type="success" @click="exportData(search, true)">全部</el-button>
                </el-popover>

                <el-button type="danger" :disabled="multipleSelection.length == 0" @click="batchDelete([])">批量删除
                </el-button>
            </el-form-item>
        </el-form>
    </div>
    <el-table :data="state.tableData" ref="multipleTableRef" style="width: 100%"
        @selection-change="handleSelectionChange" v-loading="loading" @sort-change="sortChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="150" :index="indexMethod" />
        <el-table-column prop="roleName" label="名称" sortable="custom" />
        <el-table-column prop="roleCode" label="编码" sortable="custom" />
        <el-table-column prop="roleDesc" label="描述" sortable="custom" width="200" />
        <el-table-column prop="active" label="状态" sortable="custom">
            <template v-slot="scope">
                <el-switch v-model="scope.row.active" @change="handleActive(scope.row)" />
            </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" sortable="custom" width="200" />
        <el-table-column label="操作" width="200">
            <template v-slot="scope">
                <el-button link type="primary" size="small" @click="handleOpen(scope.row)">查看</el-button>
                <el-button link type="warning" size="small" @click="handleDialog(scope.row)">修改</el-button>
                <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="Delete" icon-color="#f33516"
                    title="你确定删除吗?" @confirm="confirmEvent(scope.row)" @cancel="cancelEvent">
                    <template #reference>
                        <el-button link type="danger" size="small">删除</el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination class="page_container" :page-sizes="[10, 20, 30, 40, 50, 100, 200]" background
        layout="total, sizes, prev, pager, next, jumper" :total="state.page.total" :current-page="search.current"
        :page-size="search.size" @size-change="handleSizeChange" @current-change="handleCurrentChange" />


    <custom-form :dialogVisible="dialogVisible" :dialogTitle="dialogTitle" @getListData="getList(search)"
        :dialogData="state.form" @dialogClose="dialogVisible = false"  v-if="dialogVisible"></custom-form>

    <custom-show :dialogShow="dialogView" @close="showClose" :data="state.form"  v-if="dialogView"></custom-show>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { list, remove, add, edit, exportList, template, importData } from '@/api/role'
import { ElMessage, ElTable } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import CustomForm from './form.vue'
import CustomShow from './show.vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
// 搜索相关参数条件
let search = reactive<any>({
    roleName: "",
    active: null,
    current: 1,
    size: 10,
    // 排序
    column: null,
    asc: null,
})
// 加载条
const loading = ref(true)
// 视图对象
let state = reactive({
    tableData: [],
    page: {
        total: 0,
    },
    form: {
        id: null,
        roleName: "",
        roleDesc: "",
        roleCode: "",
        active: true,
    },
})
// 表格序号
const indexMethod = (index: number) => {
    return index + (search.current - 1) * search.size + 1;
}
onMounted(() => {
    getList(search);
})
// 获取列表数据
const getList = (async (params: any) => {
    loading.value = true
    const res = await list(params)
    state.tableData = res.data.records;
    state.page.total = res.data.total;
    loading.value = false
})
// 排序
const sortChange = (params: any) => {
    if (params.column != null) {
        search.column = params.prop;
        search.asc = params.order == 'ascending' ? true : false;
    } else {
        search.column = null;
        search.asc = null;
    }
    getList(search);
}
// 查询搜索
const onSearch = () => {
    getList(search)
}
// 重置
const resetSearch = () => {
    search.roleName = null;
    search.active = null;
    getList(search);
}
// 每页大小
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    search.size = val;
    getList(search);
}
// 当前页
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    search.current = val;
    getList(search);
}
// 初始化表单
const initFom = () => {
    state.form = {
        id: null,
        roleName: "",
        roleDesc: "",
        roleCode: "",
        active: true,
    };
}

// 激活禁用
const handleActive = async (row: any) => {
    let res: any = await edit(row);
    if (res.code != "200") {
        row.active = !row.active
    }
}

// 多选
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
    console.log(multipleSelection.value)
}
// 删除气泡确定
const confirmEvent = (row: any) => {
    let arr = [];
    arr.push(row.id);
    batchDelete(arr);
}
// 删除气泡取消
const cancelEvent = () => {
}
// 批量删除
const batchDelete = async (arr: Number[]) => {
    let res: any = {};
    if (arr != undefined && arr.length != 0) {
        res = await remove(arr);
    } else if (multipleSelection.value != undefined) {
        let arr: any[] = multipleSelection.value;
        let ids: Number[] = [];
        for (let i = 0; i < arr.length; i++) {
            ids.push(arr[i].id)
        }
        if (ids.length != 0) {
            res = await remove(ids);
        }
    }
    if (res.code == "200") {
        ElMessage.success(res.message)
        getList(search);
    }
}


// 查看
let dialogView = ref(false)
const handleOpen = (row: any) => {
    state.form = row;
    dialogView.value = true;
}
const showClose = () => {
    dialogView.value = false;
    initFom();
}

// 新增修改
let dialogVisible = ref(false)
let dialogTitle = ref("")
const handleDialog = (row: any) => {
    if (row == null) {
        dialogTitle.value = "添加角色"
        initFom();
    } else {
        dialogTitle.value = "编辑角色"
        state.form = JSON.parse(JSON.stringify(row))
    }
    dialogVisible.value = true;
}

// 导出
const exportData = async (search: any, isAll: Boolean) => {
    search.isAll = isAll;
    let res = await exportList(search);
    download(res)
    ElMessage.warning("下载中...")
}
// 模版下载
const itemplateData = async () => {
    let res = await template(search);
    download(res)
    ElMessage.warning("下载中...")
}
// 下载文件
const download = (res: any) => {
    let fileName = res.headers.requestfilename;
    fileName = decodeURIComponent(fileName);
    var blob = new Blob([res.data]);
    var requestUrl = window.URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = requestUrl;
    a.download = fileName; // 文件名称需要自己定义。如果需要知道也可以在header中自定义一个文件名称返回 也可以随机生成一个 我这里是已经提前知道了文件名
    a.click();
}
// 导入文件上传
const designUpload = async (params: any) => {
    let formData = new FormData();
    formData.append("file", params.file);
    let res: any = await importData(formData);
    if (res.code == "200") {
        ElMessage.success("导入成功")
        getList(search);
    }
    fileList.value = [];
}

const fileList = ref<UploadUserFile[]>([])
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    fileList.value = fileList.value.slice(-3)
}
</script>
<style lang="less" scoped>
.search_container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}

.page_container {
    margin-top: 15px;
    float: right;
}

.avatar {
    width: 35px;
    height: 35px;
    border-radius: 60px;
}
</style>
